package com.kehutong.contact.app;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;

import com.kehutong.contact.entity.UserApplyCompany;

import com.kehutong.common.util.AppDataPvUtils;
import com.kehutong.contact.service.DataPvService;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;
import com.kehutong.common.DoveClient;
import com.kehutong.common.TokenService;
import com.kehutong.common.dto.UniformSendReqDto;
import com.kehutong.common.entity.Root;
import com.kehutong.common.enums.MessageBusinessEnum;
import com.kehutong.common.enums.TemplateType;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.urlconfig.WebUrlConfig;
import com.kehutong.common.util.TemplateReplaceUtil;
import com.kehutong.common.util.Token;
import com.kehutong.contact.entity.ResidentHouse;
import com.kehutong.contact.entity.ResidentHouseBindApply;
import com.kehutong.contact.enums.AuditStatus;
import com.kehutong.contact.enums.BindType;
import com.kehutong.contact.enums.ResidentType;
import com.kehutong.contact.service.ResidentService;
import com.kehutong.contact.service.impl.ResidentHouseBindApplyService;
import com.kehutong.contact.util.ResidentUtil;

/**
 * 住户房屋绑定申请
 *
 * @author: liukunlong
 * @date: 2021-03-30 10:36
 */
@MvcAction
@ReqMapping("/kht-bin/crm/resident/house/bind/apply")
public class ResidentHouseBindApplyAction {
    static final Logger logger = LoggerFactory.getLogger(ResidentHouseBindApplyAction.class);

    @Inject
    private DoveClient doveClient;

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private ResidentHouseBindApplyService residentHouseBindApplyService;

    @Inject
    private ResidentService residentService;

    @Inject
    private TokenService tokenService;
    @Inject
    private WebUrlConfig webUrlConfig;

    @Inject
    private DataPvService dataPvService;


    /**
     * 根据条件住户房屋绑定申请列表
     *
     * @param jsonObject 查询条件
     * @return 住户房屋绑定申请列表
     * @throws Exception 异常
     */
    @ReqMapping("/list")
    public Object getResidentHouseBindApplyList(Token token,JSONObject jsonObject) throws Exception {
        Page<ResidentHouseBindApply> result = null;

        FindPage<ResidentHouseBindApply> find = jdbcSession.findPage(ResidentHouseBindApply.class)
                .eq(jsonObject, "id", "realname", "mobile", "status", "auditNo", "houseNo")
                .eq("deleted", false)
                .between("createTime", jsonObject, "beginTime", "endTime")
                .order("createTime", "desc")
                .page(jsonObject);
        //构建数据权限
        dataPvService.buildUserDataPv(token,jsonObject);
        find.in(jsonObject,"buildNo");

        //多小区数据权限过滤
        JSONArray communityNos=AppDataPvUtils.getAppCommunityDataPv(token,jsonObject);
        if(Objects.nonEmpty(communityNos)){
            find.in("communityNo",communityNos);
        }
        result = find.exe();
        return result;
    }

    @ReqMapping("/get")
    public Object getResidentHouseBindApply(ResidentHouseBindApply residentHouseBindApply) {
        return residentHouseBindApply;
    }

    /**
     * 绑定账户关联的物业公司编号
     *
     * @param id        账户编号
     * @param companyNo 物业公司编号
     * @throws Exception 异常
     */
    private void bindAccountCompanyNo(String id, String companyNo) throws Exception {
        JSONObject bindAccountCompanyNoResult = doveClient.post("/auth/account/service/bindAccountCompanyNo", (http) -> {
            JSONObject body = new JSONObject();
            body.put("id", id);
            body.put("companyNo", companyNo);
            http.setBody(body.toJSONString());
        });
        if (bindAccountCompanyNoResult.getIntValue("code") != 200) {
            logger.error("ResidentHouseBindApplyAction.bindAccountCompanyNo 更新账户绑定的物业公司");
        }
    }

    /**
     * 房屋认证
     * 1.绑定业主
     * 如果当前业主手机号跟后台住户房屋的类型为业主的住户信息手机号一致直接绑定。
     * 如果当前业主手机号跟后台住户房屋的类型为业主的住户信息信息中手机号不一致,或者不存在住户信息则提交给管理人员审核,审核通过如果没有住户类型业主信息，然后进行绑定房产。
     * 2.绑定家属(业主,家属,租客 属于客户的信息)
     * 如果当前申请绑定家属的手机号与当前业主下的家庭信息中存在的手机号一致则直接绑定.
     * 如果当前申请绑定家属的手机号与当前业主下的家庭信息中存在的手机号不一致或者不存在则提交业主审核,审核通过，如果没有家庭信息则创建当前业主的家庭信息，然后绑定房产
     * 3.绑定租户
     * 如果当前租户手机号跟后台租户类型类型的业主信息手机号一致直接绑定，则直接住户房产绑定。
     * 如果当前租户手机号跟后台组合信息类型的业主信息手机号不一致,或者不存在则租户信息提交给业主审核审核,审核通过创建租户类型业主信息，然后进行绑定房产。
     *
     * @param residentHouseBindApply 住户房屋绑定申请对象
     * @return 结果对象
     */
    @Bean(newInstance = true, copy = true)
    @ReqMapping("/add")
    public Object addResidentHouseBindApply(ResidentHouseBindApply residentHouseBindApply, HttpServletRequest req) throws Exception {
        Token token = tokenService.getUserToken(req);
        if (Objects.isNull(token)) {
            return Result.unlogin();
        }
        boolean userCreate = Objects.isNull(token.getUserId());
        //设置当前申请人登录账号的手机号
        residentHouseBindApply.setAccountMobile(Objects.isEmpty(residentHouseBindApply.getAccountMobile())?token.getMobile():residentHouseBindApply.getAccountMobile());
        JSONObject cropResult = doveClient.post("/admin/service/corp/get", http -> http.addParam("id",residentHouseBindApply.getCompanyNo()));
        if (cropResult.getInteger("code") != 200) {
            logger.error("getToken fail: {}", cropResult.getString("message"));
            return Result.error(0, "获取公司信息服务失败.");
        }

        //物业公司名称
        String companyName=cropResult.getJSONObject("data").getString("name");
        if(Objects.isEmpty(companyName)){
            return Result.error(0, "物业公司名称为空.");
        }

        if(Objects.isEmpty(residentHouseBindApply.getCode())){
            return Result.error(1, "短信验证码不能为空.");
        }

        //申请人的手机号已存在住户信息中(不含自己)
       /* List<Resident> residentList=jdbcSession.findArray(Resident.class)
                .eq("mobile",residentHouseBindApply.getMobile())
                .noEq("id",residentHouseBindApply.getResidentNo())
                .eq("deleted",false).exe();
        if(Objects.nonEmpty(residentList)){
            return Result.error(1, "手机号已存在.");
        }*/

        //短信发送校验
/*        JSONObject checkSmsCodeResult = doveClient.post("/auth/sms/service/checkSmsCode", (http) -> {
            JSONObject body = new JSONObject();
            body.put("sessionId",token.getSessionId());
            body.put("code",residentHouseBindApply.getCode());
            http.setBody(body.toJSONString());
        });
        if (checkSmsCodeResult.getIntValue("code") != 200) {
            return Result.error(0,checkSmsCodeResult.getString("message"));
        }*/


        //增加房屋绑定申请记录校验



        List<String> status = new ArrayList<>();
        status.add(AuditStatus.PendingAudit.getId());
        status.add(AuditStatus.PassAudit.getId());
        List<ResidentHouseBindApply> dbResidentHouseBindApplyList=jdbcSession.findArray(ResidentHouseBindApply.class)
                .eq("residentNo", residentHouseBindApply.getResidentNo())
                .eq("houseNo", residentHouseBindApply.getHouseNo())
                .eq("deleted", false)
                .in("status", status)
                .order("createTime", "desc")
                .exe();
        if (Objects.nonEmpty(dbResidentHouseBindApplyList)) {
            ResidentHouseBindApply dbResidentHouseBindApply=dbResidentHouseBindApplyList.get(0);
            if (Objects.equal(dbResidentHouseBindApply.getStatus().getId(), AuditStatus.PendingAudit.getId())) {
                return Result.error(0, "您的绑定申请正在审核中.");
            }
            //如果审核通过,住户绑定是绑定状态则不能重复认证
            if (Objects.equal(dbResidentHouseBindApply.getStatus().getId(), AuditStatus.PassAudit.getId())) {
                List<ResidentHouse> residentHouseList=jdbcSession.findArray(ResidentHouse.class)
                        .eq("residentNo", residentHouseBindApply.getResidentNo())
                        .eq("houseNo", residentHouseBindApply.getHouseNo())
                        .eq("type",dbResidentHouseBindApply.getType())
                        .eq("deleted", false)
                        .exe();
                if(Objects.nonEmpty(residentHouseList)){
                    ResidentHouse residentHouse=residentHouseList.get(0);
                    if(Objects.equal(BindType.BIND.getId(),residentHouse.getBindType().getId())){
                        return Result.error(0, "您已绑定该房屋，不能重复绑定.");
                    }
                }

            }

        }
        //绑定账户关联的物业公司编号
        bindAccountCompanyNo(residentHouseBindApply.getResidentNo(), residentHouseBindApply.getCompanyNo());

        //1 业主 2.家属 3.租客
        ResidentType residentType = residentHouseBindApply.getType();
        residentHouseBindApply.setDeleted(false);
        residentHouseBindApply.setStatus(AuditStatus.PendingAudit);
        //如果当前申请的房屋的身份是租客或家属,房屋存在业主绑定记录,则设置审核人为业主
        if (!Objects.equal(residentType.getId(), ResidentType.OWNER.getId())) {
            //查询当前房屋所属业主信息
            ResidentHouse ownerResidentHouse = jdbcSession.findOne(ResidentHouse.class)
                    .eq("houseNo", residentHouseBindApply.getHouseNo())
                    .eq("type", ResidentType.OWNER)
                    .eq("bindType", BindType.BIND)
                    .eq("deleted", false)
                    .exe();
            if (Objects.nonNull(ownerResidentHouse)) {
                residentHouseBindApply.setAuditNo(ownerResidentHouse.getResidentNo());
                residentHouseBindApply.setAuditName(ownerResidentHouse.getRealname());
                residentHouseBindApply.setAuditAvatar(ownerResidentHouse.getAvatar());
                residentHouseBindApply.setPid(ownerResidentHouse.getId());
                residentHouseBindApply.setPname(ownerResidentHouse.getRealname());
            } else {
                //当前申请认证家属的房屋业主还没有认证则挺尸
                if (Objects.equal(residentType.getId(), ResidentType.FRIEND.getId())) {
                    ResidentHouse unBindOwnerResidentHouse = jdbcSession.findOne(ResidentHouse.class)
                            .eq("houseNo", residentHouseBindApply.getHouseNo())
                            .eq("type", ResidentType.OWNER)
                            .eq("bindType", BindType.NO_BIND)
                            .eq("deleted", false)
                            .exe();
                    if (Objects.nonNull(unBindOwnerResidentHouse)) {
                        return Result.error(0, "当前房屋业主没有认证.");
                    }else{
                        return Result.error(0, "当前房屋业主不存在.");
                    }
                }
                //设置租客的出租人名称
                residentHouseBindApply.setPid(Root.ROOT_ID);
                residentHouseBindApply.setPname(companyName);
            }

        } else {
            //如果是业主设置申请记录的pid(住户房屋绑定编号),pname(系名称,或业主名称)
            residentHouseBindApply.setPid(Root.ROOT_ID);
            residentHouseBindApply.setPname(companyName);
        }

        // 保存用户申请的企业编号
        logger.info("登录用户id=" + token.getUuid());
        UserApplyCompany userApplyCompany = jdbcSession.findById(UserApplyCompany.class, token.getUuid());
        if (userApplyCompany == null) {
            userApplyCompany = Pool.newInstance(UserApplyCompany.class, token.getUuid());
            userApplyCompany.setUserId(token.getUuid());
            userApplyCompany.setCompanyNo(residentHouseBindApply.getCompanyNo());
            jdbcSession.insert(userApplyCompany);
        } else {
            userApplyCompany.setUserId(token.getUuid());
            userApplyCompany.setCompanyNo(residentHouseBindApply.getCompanyNo());
            jdbcSession.updateById(userApplyCompany);
        }

        //如果当前类型的住户有没有绑定过房屋,如果一次都没有则直接提交申请
        JSONArray bindTypeJsonArray=new JSONArray();
        bindTypeJsonArray.add(BindType.NO_BIND.getId());
        bindTypeJsonArray.add(BindType.BIND.getId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", residentType.getId());
        jsonObject.put("houseNo", residentHouseBindApply.getHouseNo());
        jsonObject.put("bindType",bindTypeJsonArray);
        jsonObject.put("residentNo",residentHouseBindApply.getResidentNo());
        Page<ResidentHouse> residentHousePage = residentService.getResidentHouseList(jsonObject);
        List<ResidentHouse> residentHouseList = residentHousePage.getList();
        if (Objects.isEmpty(residentHouseList)) {
            jdbcSession.insert(residentHouseBindApply);
            //如果当前申请是通过业主二维码分享过来,则直接审核通过
            if (Objects.nonEmpty(residentHouseBindApply.getOwnerNo()) && !Objects.equal(ResidentType.OWNER.getId(), residentHouseBindApply.getType().getId())) {
                ResidentHouse ownerHouse = jdbcSession.findOne(ResidentHouse.class)
                        .eq("residentNo", residentHouseBindApply.getOwnerNo())
                        .eq("houseNo", residentHouseBindApply.getHouseNo())
                        .eq("type", ResidentType.OWNER.getId())
                        .eq("bindType", BindType.BIND.getId())
                        .eq("deleted", false)
                        .exe();
                if (Objects.nonNull(ownerHouse)) {
                    //TODO 消息提醒(新增家属租客自动审核) 审核通过
                    try {
                        if (userCreate)
                            msgUniformSend(residentHouseBindApply, residentHouseBindApply.getAuditNo(), true, TemplateType.RESIDENT_C_AUDIT_SUCCESS, Arrays.asList(residentHouseBindApply.getMobile()), true);
                        //TODO 根据楼栋给管家发消息，管家ID
                        /*
                        Set<String> managerIdList = ResidentUtil.getManagerIdList(residentHouseBindApply.getBuildNo(), residentHouseBindApply.getHouseType().getId());
                        for (String each : managerIdList) {
                            msgUniformSend(residentHouseBindApply, each, userCreate, TemplateType.RESIDENT_B_ADD, false);
                        }*/
                    } catch (Exception e){
                        logger.error(e.getMessage(), e);
                    }

                    ResidentHouseBindApply auditResidentHouseBindApply = jdbcSession.findById(ResidentHouseBindApply.class, residentHouseBindApply.getId());
                    auditResidentHouseBindApply.setStatus(AuditStatus.PassAudit);
                    auditResidentHouseBindApply.setAuditNo(ownerHouse.getResidentNo());
                    auditResidentHouseBindApply.setAuditName(ownerHouse.getRealname());
                    auditResidentHouseBindApply.setAuditTime(LocalDateTime.now());
                    auditResidentHouseBindApply.setAuditRemarks("业主二维码分享住户认证自动审核通过");
                    residentHouseBindApplyService.auditResidentHouseBindApply(auditResidentHouseBindApply);
                    return Result.success(true);
                }
            }
            //TODO 消息提醒(业主或后台审核)  待审核
            try {
                // 管家  遍历
                Set<String> managerIdList = ResidentUtil.getManagerIdList(residentHouseBindApply.getBuildNo(), residentHouseBindApply.getHouseType().getId());
                for (String each : managerIdList) {
                    msgUniformSend(residentHouseBindApply, each, false, TemplateType.RESIDENT_B_AUDIT, true);
                }
            } catch (Exception e) {
                logger.error("发送消息："+e.getMessage(), e);
            }
            return Result.success(false);
        }


        //手机号+"真实姓名"与住户编号映射(匹配规则姓名+手机) 匹配房屋数据的绑定状态是是未绑定,已绑定（系统初始化录入的数据未未绑定）
        Map<String, ResidentHouse> mapping = new HashMap<>();
        for (ResidentHouse residentHouse : residentHouseList) {
                //真实姓名
                String realname = residentHouse.getRealname();

                //手机号
                String mobile = residentHouse.getMobile();

                mapping.put(realname + mobile, residentHouse);
        }

        //绑定认证类型房屋与当前住户手机号不符合则提交申请
        if (!mapping.containsKey(residentHouseBindApply.getRealname() + residentHouseBindApply.getMobile())) {
            //TODO 消息提醒(需要审核的) 待审核
            if (userCreate) {
                // 业主暂时不用审核提醒
            } else {
                try {
                    // 管家
                    Set<String> managerIdList = ResidentUtil.getManagerIdList(residentHouseBindApply.getBuildNo(), residentHouseBindApply.getHouseType().getId());
                    for (String each : managerIdList) {
                        msgUniformSend(residentHouseBindApply, each, false, TemplateType.RESIDENT_B_AUDIT, true);
                    }
                } catch (Exception e) {
                    logger.error("发送消息："+e.getMessage(), e);
                }

            }
            jdbcSession.insert(residentHouseBindApply);
            return Result.success(false);
        }



        //符合规则的默认审核通过增加申请记录,系统自动审核
        jdbcSession.insert(residentHouseBindApply);
        residentHouseBindApply.setStatus(AuditStatus.PassAudit);
        residentHouseBindApply.setAuditNo(Root.ROOT_ID);
        residentHouseBindApply.setAuditName("系统审核");
        residentHouseBindApply.setAuditTime(LocalDateTime.now());
        residentHouseBindApply.setAuditRemarks("符合匹配规则系统自动审核");
        residentHouseBindApplyService.auditResidentHouseBindApply(residentHouseBindApply);
        //TODO 消息提醒(新增业主自动审核) 审核通过
        /*
        if (!userCreate) {
            try {
                // 管家 遍历
                // 管家
                Set<String> managerIdList = ResidentUtil.getManagerIdList(residentHouseBindApply.getBuildNo(), residentHouseBindApply.getHouseType().getId());
                for (String each : managerIdList) {
                    msgUniformSend(residentHouseBindApply, each, userCreate, TemplateType.RESIDENT_B_ADD, false);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }*/
        return Result.success(true);
    }

    private void msgUniformSend(ResidentHouseBindApply apply, String uuid, boolean userCreate, TemplateType templateType, boolean isAudit) throws Exception {
        msgUniformSend(apply, uuid, userCreate, templateType, null, isAudit);
    }

    private void msgUniformSend(ResidentHouseBindApply apply, String uuid, boolean userCreate, TemplateType templateType, List<String> phoneList, boolean isAudit) throws Exception {
        // 获取消息推送配置文件
        JSONObject configJson = doveClient.post("/crm/message/global/config/service/get", (http) -> {
            http.addParam("templateType", templateType.getId());
        });

        if (configJson.getIntValue("code") == 200) {
            UniformSendReqDto dto = getUniformSendReqDto(apply, uuid, userCreate, templateType, phoneList, configJson.getJSONObject("data"), isAudit);
            // 消息推送
            doveClient.post("/crm/message/service/uniformSend", (http) -> {
                http.addParam("temp", JSONObject.toJSONString(dto));
            });
        }
    }

    private UniformSendReqDto getUniformSendReqDto(ResidentHouseBindApply apply, String uuid, boolean userCreate, TemplateType templateType, List<String> phoneList, JSONObject dataJson, boolean isAudit) throws Exception {
        logger.info("action.msgUniformSend.apply参数：{}", apply.toString());
        UniformSendReqDto dto = new UniformSendReqDto();
        dto.setMsgId(apply.getId());
        dto.setBusinessTypeId(MessageBusinessEnum.MSG_RESIDENT.getId());
        dto.setTemplateTypeId(templateType.getId());
        dto.setCompanyNo(apply.getCompanyNo());
        dto.setUserCreate(userCreate);
        dto.setUuid(uuid);
        dto.setTitle("住户消息");

        JSONObject inner = dataJson.getJSONObject("messageTemplateInner");
        if (dataJson.getBooleanValue("innerSend") && Objects.nonNull(inner)) {
            dto.setTitle(inner.getString("title"));
            dto.setInnerData(TemplateReplaceUtil.replace(inner.getString("content"), inner.getString("tagArray"), apply));
        }

        JSONObject app = dataJson.getJSONObject("messageTemplateApp");
        if (dataJson.getBooleanValue("appSend") && Objects.nonNull(app)) {
            dto.setTitle(app.getString("title"));
            dto.setAppData(TemplateReplaceUtil.replace(app.getString("content"), app.getString("tagArray"), apply));
            if (isAudit) {
                dto.setAppToUrl(webUrlConfig.getUrl("/web-app/?page=audit/" + apply.getId()));
            } else {
                dto.setAppToUrl(webUrlConfig.getUrl("/web-app/?page=resident/portrait/" + apply.getId()));
            }
        }

        JSONObject sms = dataJson.getJSONObject("messageTemplateSms");
        if (dataJson.getBooleanValue("smsSend") && Objects.nonNull(sms)) {
            if (Objects.nonEmpty(phoneList)){
                dto.setPhoneList(phoneList);
                dto.setSmsDataParams(TemplateReplaceUtil.listTencentSmsParam(sms.getString("content"), sms.getString("tagArray"), apply));
            } else {
                JSONObject jsonObject = doveClient.post("/kht-bin/auth/user/listPhone", http -> {
                    JSONObject temp = new JSONObject();
                    temp.put("id", Arrays.asList(uuid));
                    http.setBody(temp.toJSONString());
                });
                List<String> listPhone = JSONArray.parseArray(jsonObject.getString("data"), String.class);
                if (Objects.nonEmpty(listPhone)){
                    dto.setPhoneList(listPhone);
                    dto.setSmsDataParams(TemplateReplaceUtil.listTencentSmsParam(sms.getString("content"), sms.getString("tagArray"), apply));
                }
            }
        }

        String wxchatTemplate = dataJson.getString("wxchatTemplate");
        if (dataJson.getBooleanValue("wxchatSend") && Objects.nonNull(wxchatTemplate)) {
            dto.setWxChatData(getWxchatTemplate(templateType, apply));
        }
        return dto;
    }

    private String getWxchatTemplate(TemplateType templateType, ResidentHouseBindApply apply){
        JSONObject data = new JSONObject();

        if(TemplateType.RESIDENT_C_AUDIT_SUCCESS == templateType){
            data.put("first", buildMpMessageData("您的住户申请已通过"));
            // 小区名称
            data.put("keyword1", buildMpMessageData(apply.getCommunityName()));
            // 房间号
            data.put("keyword2", buildMpMessageData(apply.getHouseName()));
            // 关系
            data.put("keyword3", buildMpMessageData(apply.getRelationType().getDesc()));

            data.put("remark", buildMpMessageData("祝您生活愉快！"));
            return data.toJSONString();
        } else {
            return null;
        }
    }

    private JSONObject buildMpMessageData(String value) {
        JSONObject json = new JSONObject();
        json.put("value", value);
        return json;
    }


    /**
     * 业主审核住户房屋绑定申请
     *
     * @param residentHouseBindApply 住户房屋绑定申请对象
     * @return 操作结果
     * @throws Exception 异常
     */
    @Bean(copy = true)
    @ReqMapping("/audit")
    public Object auditResidentHouseBindApply(ResidentHouseBindApply residentHouseBindApply, HttpServletRequest req) throws Exception {
        Token token = tokenService.getUserToken(req);
        if (Objects.isNull(token)) {
            return Result.error(0, "当前用户未登录.");
        }
        residentHouseBindApply.setAuditNo(token.getUuid());
        residentHouseBindApply.setAuditName(token.getUsername());
        residentHouseBindApply.setAuditAvatar(token.getHeadUrl());
        residentHouseBindApply.setAuditTime(LocalDateTime.now());
        return residentHouseBindApplyService.auditResidentHouseBindApply(residentHouseBindApply);
    }

    /**
     * 审核校验住户房屋绑定申请
     *
     * @param residentHouseBindApply 住户房屋绑定申请对象
     * @return 操作结果
     * @throws Exception 异常
     */
    @Bean(copy = true)
    @ReqMapping("/audit/verify")
    public Object auditVerifyResidentHouseBindApply(ResidentHouseBindApply residentHouseBindApply, HttpServletRequest req) throws Exception {
//        Token token = tokenService.getUserToken(req);
        List<String> bindTypeList = new ArrayList<>();
        bindTypeList.add(BindType.NO_BIND.getId());
        bindTypeList.add(BindType.BIND.getId());

        if (Objects.equal(residentHouseBindApply.getType().getId(), ResidentType.OWNER.getId())) {
            ResidentHouse bindResidentHouse = jdbcSession.findOne(ResidentHouse.class)
                    .eq("houseNo", residentHouseBindApply.getHouseNo())
                    .eq("type", residentHouseBindApply.getType())
                    .eq("deleted", false)
                    .in("bindType", bindTypeList)
                    .eq("deleted", false)
                    .exe();
            if (Objects.isNull(bindResidentHouse)) {
                return Result.error(0, "当前房屋没有绑定过数据");
            }
            if (Objects.equal(bindResidentHouse.getResidentNo(), residentHouseBindApply.getResidentNo())) {
                if (!Objects.equal(residentHouseBindApply.getMobile(), bindResidentHouse.getMobile())) {
                    return Result.error(0, "手机号不一致");
                } else if (!Objects.equal(residentHouseBindApply.getRealname(), bindResidentHouse.getRealname())) {
                    return Result.error(0, "姓名不一致");
                }
            } else {
                if (Objects.equal(bindResidentHouse.getBindType().getId(), BindType.NO_BIND.getId())) {
                    return Result.error(0, "当前房屋已存在不属于当前申请人的未绑定记录");
                }
                if (Objects.equal(bindResidentHouse.getBindType().getId(), BindType.BIND.getId())) {
                    return Result.error(0, "当前房屋已存在不属于当前申请人的绑定记录");
                }
            }

        } else {
            ResidentHouse bindResidentHouse = jdbcSession.findOne(ResidentHouse.class)
                    .eq("residentNo", residentHouseBindApply.getResidentNo())
                    .eq("houseNo", residentHouseBindApply.getHouseNo())
                    .eq("type", residentHouseBindApply.getType())
                    .eq("deleted", false)
                    .in("bindType", bindTypeList)
                    .exe();
            if (Objects.isNull(bindResidentHouse)) {
                return Result.error(0, "房屋没有绑定过数据.");
            }else{
                if (!Objects.equal(residentHouseBindApply.getMobile(), bindResidentHouse.getMobile())) {
                    return Result.error(0, "手机号不一致");
                } else if (!Objects.equal(residentHouseBindApply.getRealname(), bindResidentHouse.getRealname())) {
                    return Result.error(0, "姓名不一致");
                }
            }
        }
        return Result.success();
    }

    /**
     * 更新住户房屋绑定申请
     *
     * @param residentHouseBindApply 住户房屋绑定申请对象
     * @return 操作结果
     * @throws Exception 异常
     */
    @Bean(copy = true)
    @ReqMapping("/update")
    public Object updateResidentHouseBindApply(ResidentHouseBindApply residentHouseBindApply) throws Exception {
        if (Objects.isNull(residentHouseBindApply.getId())) {
            Result.error(1, "申请编号不能为空");
        }
        jdbcSession.updateById(residentHouseBindApply);
        return Result.success();
    }


    /**
     * 删除住户房屋绑定申请
     *
     * @param residentHouseBindApply 住户房屋绑定申请对象
     * @return 操作结果
     * @throws Exception 异常
     */
    @ReqMapping("/delete")
    public Object deleteResidentHouseBindApply(ResidentHouseBindApply residentHouseBindApply) throws Exception {
        if (Objects.isNull(residentHouseBindApply)) {
            Result.error(1, "参数不能为空");
        }
        residentHouseBindApply.setDeleted(true);
        jdbcSession.updateById(residentHouseBindApply);
        return Result.success();
    }

}
